package com.hmall.user.interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.hmall.common.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  获取请求头
        String authorization = request.getHeader("authorization");
        // 存入ThreadLocal
        // 判断是否登录
        if (StringUtils.isBlank(authorization)) {
            // 没有用户信息，未登录  403：禁止
            response.setStatus(403);
            System.err.println("用户未登录");
            throw new RuntimeException("用户未登录");
        }
        if (authorization.equals("2")) {
            System.err.println("用户：2");
            // 已登录：放行
            return true;
        }
        // 未登录：拦截
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
